<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Managers &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../index.html" />
    <link rel="up" title="Models and databases" href="index.html" />
    <link rel="next" title="Performing raw SQL queries" href="sql.html" />
    <link rel="prev" title="Aggregation" href="aggregation.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="aggregation.html" title="Aggregation">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="sql.html" title="Performing raw SQL queries">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-managers">
            
  <div class="section" id="s-managers">
<span id="managers"></span><h1>Managers<a class="headerlink" href="#managers" title="Permalink to this headline">¶</a></h1>
<dl class="class">
<dt id="django.db.models.Manager">
<em class="property">class </em><tt class="descname">Manager</tt><a class="headerlink" href="#django.db.models.Manager" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A <tt class="docutils literal"><span class="pre">Manager</span></tt> is the interface through which database query operations are
provided to Django models. At least one <tt class="docutils literal"><span class="pre">Manager</span></tt> exists for every model in
a Django application.</p>
<p>The way <tt class="docutils literal"><span class="pre">Manager</span></tt> classes work is documented in <a class="reference internal" href="queries.html"><em>Making queries</em></a>;
this document specifically touches on model options that customize <tt class="docutils literal"><span class="pre">Manager</span></tt>
behavior.</p>
<div class="section" id="s-manager-names">
<span id="s-id1"></span><span id="manager-names"></span><span id="id1"></span><h2>Manager names<a class="headerlink" href="#manager-names" title="Permalink to this headline">¶</a></h2>
<p>By default, Django adds a <tt class="docutils literal"><span class="pre">Manager</span></tt> with the name <tt class="docutils literal"><span class="pre">objects</span></tt> to every Django
model class. However, if you want to use <tt class="docutils literal"><span class="pre">objects</span></tt> as a field name, or if you
want to use a name other than <tt class="docutils literal"><span class="pre">objects</span></tt> for the <tt class="docutils literal"><span class="pre">Manager</span></tt>, you can rename
it on a per-model basis. To rename the <tt class="docutils literal"><span class="pre">Manager</span></tt> for a given class, define a
class attribute of type <tt class="docutils literal"><span class="pre">models.Manager()</span></tt> on that model. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c">#...</span>
    <span class="n">people</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">()</span>
</pre></div>
</div>
<p>Using this example model, <tt class="docutils literal"><span class="pre">Person.objects</span></tt> will generate an
<tt class="docutils literal"><span class="pre">AttributeError</span></tt> exception, but <tt class="docutils literal"><span class="pre">Person.people.all()</span></tt> will provide a list
of all <tt class="docutils literal"><span class="pre">Person</span></tt> objects.</p>
</div>
<div class="section" id="s-custom-managers">
<span id="s-id2"></span><span id="custom-managers"></span><span id="id2"></span><h2>Custom Managers<a class="headerlink" href="#custom-managers" title="Permalink to this headline">¶</a></h2>
<p>You can use a custom <tt class="docutils literal"><span class="pre">Manager</span></tt> in a particular model by extending the base
<tt class="docutils literal"><span class="pre">Manager</span></tt> class and instantiating your custom <tt class="docutils literal"><span class="pre">Manager</span></tt> in your model.</p>
<p>There are two reasons you might want to customize a <tt class="docutils literal"><span class="pre">Manager</span></tt>: to add extra
<tt class="docutils literal"><span class="pre">Manager</span></tt> methods, and/or to modify the initial <tt class="docutils literal"><span class="pre">QuerySet</span></tt> the <tt class="docutils literal"><span class="pre">Manager</span></tt>
returns.</p>
<div class="section" id="s-adding-extra-manager-methods">
<span id="adding-extra-manager-methods"></span><h3>Adding extra Manager methods<a class="headerlink" href="#adding-extra-manager-methods" title="Permalink to this headline">¶</a></h3>
<p>Adding extra <tt class="docutils literal"><span class="pre">Manager</span></tt> methods is the preferred way to add &#8220;table-level&#8221;
functionality to your models. (For &#8220;row-level&#8221; functionality &#8211; i.e., functions
that act on a single instance of a model object &#8211; use <a class="reference internal" href="models.html#model-methods"><em>Model methods</em></a>, not custom <tt class="docutils literal"><span class="pre">Manager</span></tt> methods.)</p>
<p>A custom <tt class="docutils literal"><span class="pre">Manager</span></tt> method can return anything you want. It doesn&#8217;t have to
return a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
<p>For example, this custom <tt class="docutils literal"><span class="pre">Manager</span></tt> offers a method <tt class="docutils literal"><span class="pre">with_counts()</span></tt>, which
returns a list of all <tt class="docutils literal"><span class="pre">OpinionPoll</span></tt> objects, each with an extra
<tt class="docutils literal"><span class="pre">num_responses</span></tt> attribute that is the result of an aggregate query:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">PollManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">with_counts</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">connection</span>
        <span class="n">cursor</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
        <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;&quot;&quot;</span>
<span class="s">            SELECT p.id, p.question, p.poll_date, COUNT(*)</span>
<span class="s">            FROM polls_opinionpoll p, polls_response r</span>
<span class="s">            WHERE p.id = r.poll_id</span>
<span class="s">            GROUP BY p.id, p.question, p.poll_date</span>
<span class="s">            ORDER BY p.poll_date DESC&quot;&quot;&quot;</span><span class="p">)</span>
        <span class="n">result_list</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">():</span>
            <span class="n">p</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">question</span><span class="o">=</span><span class="n">row</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">poll_date</span><span class="o">=</span><span class="n">row</span><span class="p">[</span><span class="mi">2</span><span class="p">])</span>
            <span class="n">p</span><span class="o">.</span><span class="n">num_responses</span> <span class="o">=</span> <span class="n">row</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span>
            <span class="n">result_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">p</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">result_list</span>

<span class="k">class</span> <span class="nc">OpinionPoll</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">poll_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">PollManager</span><span class="p">()</span>

<span class="k">class</span> <span class="nc">Response</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">poll</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">OpinionPoll</span><span class="p">)</span>
    <span class="n">person_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>
</pre></div>
</div>
<p>With this example, you&#8217;d use <tt class="docutils literal"><span class="pre">OpinionPoll.objects.with_counts()</span></tt> to return
that list of <tt class="docutils literal"><span class="pre">OpinionPoll</span></tt> objects with <tt class="docutils literal"><span class="pre">num_responses</span></tt> attributes.</p>
<p>Another thing to note about this example is that <tt class="docutils literal"><span class="pre">Manager</span></tt> methods can
access <tt class="docutils literal"><span class="pre">self.model</span></tt> to get the model class to which they&#8217;re attached.</p>
</div>
<div class="section" id="s-modifying-initial-manager-querysets">
<span id="modifying-initial-manager-querysets"></span><h3>Modifying initial Manager QuerySets<a class="headerlink" href="#modifying-initial-manager-querysets" title="Permalink to this headline">¶</a></h3>
<p>A <tt class="docutils literal"><span class="pre">Manager</span></tt>’s base <tt class="docutils literal"><span class="pre">QuerySet</span></tt> returns all objects in the system. For
example, using this model:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">author</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
</pre></div>
</div>
<p>...the statement <tt class="docutils literal"><span class="pre">Book.objects.all()</span></tt> will return all books in the database.</p>
<p>You can override a <tt class="docutils literal"><span class="pre">Manager</span></tt>’s base <tt class="docutils literal"><span class="pre">QuerySet</span></tt> by overriding the
<tt class="docutils literal"><span class="pre">Manager.get_queryset()</span></tt> method. <tt class="docutils literal"><span class="pre">get_queryset()</span></tt> should return a
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> with the properties you require.</p>
<p>For example, the following model has <em>two</em> <tt class="docutils literal"><span class="pre">Manager</span></tt>s &#8211; one that returns
all objects, and one that returns only the books by Roald Dahl:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># First, define the Manager subclass.</span>
<span class="k">class</span> <span class="nc">DahlBookManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">get_queryset</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">DahlBookManager</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">get_queryset</span><span class="p">()</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">author</span><span class="o">=</span><span class="s">&#39;Roald Dahl&#39;</span><span class="p">)</span>

<span class="c"># Then hook it into the Book model explicitly.</span>
<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">author</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>

    <span class="n">objects</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">()</span> <span class="c"># The default manager.</span>
    <span class="n">dahl_objects</span> <span class="o">=</span> <span class="n">DahlBookManager</span><span class="p">()</span> <span class="c"># The Dahl-specific manager.</span>
</pre></div>
</div>
<p>With this sample model, <tt class="docutils literal"><span class="pre">Book.objects.all()</span></tt> will return all books in the
database, but <tt class="docutils literal"><span class="pre">Book.dahl_objects.all()</span></tt> will only return the ones written by
Roald Dahl.</p>
<p>Of course, because <tt class="docutils literal"><span class="pre">get_queryset()</span></tt> returns a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> object, you can
use <tt class="docutils literal"><span class="pre">filter()</span></tt>, <tt class="docutils literal"><span class="pre">exclude()</span></tt> and all the other <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods on it.
So these statements are all legal:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Book</span><span class="o">.</span><span class="n">dahl_objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="n">Book</span><span class="o">.</span><span class="n">dahl_objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&#39;Matilda&#39;</span><span class="p">)</span>
<span class="n">Book</span><span class="o">.</span><span class="n">dahl_objects</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
</pre></div>
</div>
<p>This example also pointed out another interesting technique: using multiple
managers on the same model. You can attach as many <tt class="docutils literal"><span class="pre">Manager()</span></tt> instances to
a model as you&#8217;d like. This is an easy way to define common &#8220;filters&#8221; for your
models.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">AuthorManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">get_queryset</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">AuthorManager</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">get_queryset</span><span class="p">()</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">role</span><span class="o">=</span><span class="s">&#39;A&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">EditorManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">get_queryset</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">EditorManager</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">get_queryset</span><span class="p">()</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">role</span><span class="o">=</span><span class="s">&#39;E&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">role</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="p">((</span><span class="s">&#39;A&#39;</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s">&#39;Author&#39;</span><span class="p">)),</span> <span class="p">(</span><span class="s">&#39;E&#39;</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s">&#39;Editor&#39;</span><span class="p">))))</span>
    <span class="n">people</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">()</span>
    <span class="n">authors</span> <span class="o">=</span> <span class="n">AuthorManager</span><span class="p">()</span>
    <span class="n">editors</span> <span class="o">=</span> <span class="n">EditorManager</span><span class="p">()</span>
</pre></div>
</div>
<p>This example allows you to request <tt class="docutils literal"><span class="pre">Person.authors.all()</span></tt>, <tt class="docutils literal"><span class="pre">Person.editors.all()</span></tt>,
and <tt class="docutils literal"><span class="pre">Person.people.all()</span></tt>, yielding predictable results.</p>
<div class="section" id="s-default-managers">
<span id="s-id3"></span><span id="default-managers"></span><span id="id3"></span><h4>Default managers<a class="headerlink" href="#default-managers" title="Permalink to this headline">¶</a></h4>
<p>If you use custom <tt class="docutils literal"><span class="pre">Manager</span></tt> objects, take note that the first <tt class="docutils literal"><span class="pre">Manager</span></tt>
Django encounters (in the order in which they&#8217;re defined in the model) has a
special status. Django interprets the first <tt class="docutils literal"><span class="pre">Manager</span></tt> defined in a class as
the &#8220;default&#8221; <tt class="docutils literal"><span class="pre">Manager</span></tt>, and several parts of Django
(including <a class="reference internal" href="../../ref/django-admin.html#django-admin-dumpdata"><tt class="xref std std-djadmin docutils literal"><span class="pre">dumpdata</span></tt></a>) will use that <tt class="docutils literal"><span class="pre">Manager</span></tt>
exclusively for that model. As a result, it&#8217;s a good idea to be careful in
your choice of default manager in order to avoid a situation where overriding
<tt class="docutils literal"><span class="pre">get_queryset()</span></tt> results in an inability to retrieve objects you&#8217;d like to
work with.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p>The <tt class="docutils literal"><span class="pre">get_queryset</span></tt> method was previously named <tt class="docutils literal"><span class="pre">get_query_set</span></tt>.</p>
</div>
</div>
<div class="section" id="s-using-managers-for-related-object-access">
<span id="s-managers-for-related-objects"></span><span id="using-managers-for-related-object-access"></span><span id="managers-for-related-objects"></span><h4>Using managers for related object access<a class="headerlink" href="#using-managers-for-related-object-access" title="Permalink to this headline">¶</a></h4>
<p>By default, Django uses an instance of a &#8220;plain&#8221; manager class when accessing
related objects (i.e. <tt class="docutils literal"><span class="pre">choice.poll</span></tt>), not the default manager on the related
object. This is because Django needs to be able to retrieve the related
object, even if it would otherwise be filtered out (and hence be inaccessible)
by the default manager.</p>
<p>If the normal plain manager class (<a class="reference internal" href="#django.db.models.Manager" title="django.db.models.Manager"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.Manager</span></tt></a>) is not
appropriate for your circumstances, you can force Django to use the same class
as the default manager for your model by setting the <tt class="docutils literal"><span class="pre">use_for_related_fields</span></tt>
attribute on the manager class. This is documented fully <a class="reference internal" href="#manager-types">below</a>.</p>
</div>
</div>
<div class="section" id="s-calling-custom-queryset-methods-from-the-manager">
<span id="s-calling-custom-queryset-methods-from-manager"></span><span id="calling-custom-queryset-methods-from-the-manager"></span><span id="calling-custom-queryset-methods-from-manager"></span><h3>Calling custom <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods from the <tt class="docutils literal"><span class="pre">Manager</span></tt><a class="headerlink" href="#calling-custom-queryset-methods-from-the-manager" title="Permalink to this headline">¶</a></h3>
<p>While most methods from the standard <tt class="docutils literal"><span class="pre">QuerySet</span></tt> are accessible directly from
the <tt class="docutils literal"><span class="pre">Manager</span></tt>, this is only the case for the extra methods defined on a
custom <tt class="docutils literal"><span class="pre">QuerySet</span></tt> if you also implement them on the <tt class="docutils literal"><span class="pre">Manager</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">PersonQuerySet</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">QuerySet</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">authors</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">role</span><span class="o">=</span><span class="s">&#39;A&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">editors</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">role</span><span class="o">=</span><span class="s">&#39;E&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">PersonManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">get_queryset</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">PersonQuerySet</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">_db</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">authors</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_queryset</span><span class="p">()</span><span class="o">.</span><span class="n">authors</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">editors</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_queryset</span><span class="p">()</span><span class="o">.</span><span class="n">editors</span><span class="p">()</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">role</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="p">((</span><span class="s">&#39;A&#39;</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s">&#39;Author&#39;</span><span class="p">)),</span> <span class="p">(</span><span class="s">&#39;E&#39;</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s">&#39;Editor&#39;</span><span class="p">))))</span>
    <span class="n">people</span> <span class="o">=</span> <span class="n">PersonManager</span><span class="p">()</span>
</pre></div>
</div>
<p>This example allows you to call both <tt class="docutils literal"><span class="pre">authors()</span></tt> and <tt class="docutils literal"><span class="pre">editors()</span></tt> directly from
the manager <tt class="docutils literal"><span class="pre">Person.people</span></tt>.</p>
</div>
<div class="section" id="s-creating-manager-with-queryset-methods">
<span id="s-create-manager-with-queryset-methods"></span><span id="creating-manager-with-queryset-methods"></span><span id="create-manager-with-queryset-methods"></span><h3>Creating <tt class="docutils literal"><span class="pre">Manager</span></tt> with <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods<a class="headerlink" href="#creating-manager-with-queryset-methods" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.7.</span> </div>
<p>In lieu of the above approach which requires duplicating methods on both the
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> and the <tt class="docutils literal"><span class="pre">Manager</span></tt>, <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.as_manager" title="django.db.models.query.QuerySet.as_manager"><tt class="xref py py-meth docutils literal"><span class="pre">QuerySet.as_manager()</span></tt></a> can be used to create an instance
of <tt class="docutils literal"><span class="pre">Manager</span></tt> with a copy of a custom <tt class="docutils literal"><span class="pre">QuerySet</span></tt>’s methods:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="n">people</span> <span class="o">=</span> <span class="n">PersonQuerySet</span><span class="o">.</span><span class="n">as_manager</span><span class="p">()</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">Manager</span></tt> instance created by <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.as_manager" title="django.db.models.query.QuerySet.as_manager"><tt class="xref py py-meth docutils literal"><span class="pre">QuerySet.as_manager()</span></tt></a> will be virtually
identical to the <tt class="docutils literal"><span class="pre">PersonManager</span></tt> from the previous example.</p>
<p>Not every <tt class="docutils literal"><span class="pre">QuerySet</span></tt> method makes sense at the <tt class="docutils literal"><span class="pre">Manager</span></tt> level; for
instance we intentionally prevent the <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.delete" title="django.db.models.query.QuerySet.delete"><tt class="xref py py-meth docutils literal"><span class="pre">QuerySet.delete()</span></tt></a> method from being copied onto
the <tt class="docutils literal"><span class="pre">Manager</span></tt> class.</p>
<p>Methods are copied according to the following rules:</p>
<ul class="simple">
<li>Public methods are copied by default.</li>
<li>Private methods (starting with an underscore) are not copied by default.</li>
<li>Methods with a <tt class="docutils literal"><span class="pre">queryset_only</span></tt> attribute set to <tt class="docutils literal"><span class="pre">False</span></tt> are always copied.</li>
<li>Methods with a <tt class="docutils literal"><span class="pre">queryset_only</span></tt> attribute set to <tt class="docutils literal"><span class="pre">True</span></tt> are never copied.</li>
</ul>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">CustomQuerySet</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">QuerySet</span><span class="p">):</span>
    <span class="c"># Available on both Manager and QuerySet.</span>
    <span class="k">def</span> <span class="nf">public_method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span>

    <span class="c"># Available only on QuerySet.</span>
    <span class="k">def</span> <span class="nf">_private_method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span>

    <span class="c"># Available only on QuerySet.</span>
    <span class="k">def</span> <span class="nf">opted_out_public_method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span>
    <span class="n">opted_out_public_method</span><span class="o">.</span><span class="n">queryset_only</span> <span class="o">=</span> <span class="bp">True</span>

    <span class="c"># Available on both Manager and QuerySet.</span>
    <span class="k">def</span> <span class="nf">_opted_in_private_method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span>
    <span class="n">_opted_in_private_method</span><span class="o">.</span><span class="n">queryset_only</span> <span class="o">=</span> <span class="bp">False</span>
</pre></div>
</div>
<div class="section" id="s-from-queryset">
<span id="from-queryset"></span><h4>from_queryset<a class="headerlink" href="#from-queryset" title="Permalink to this headline">¶</a></h4>
<dl class="classmethod">
<dt id="django.db.models.from_queryset">
<em class="property">classmethod </em><tt class="descname">from_queryset</tt>(<em>queryset_class</em>)<a class="headerlink" href="#django.db.models.from_queryset" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>For advanced usage you might want both a custom <tt class="docutils literal"><span class="pre">Manager</span></tt> and a custom
<tt class="docutils literal"><span class="pre">QuerySet</span></tt>. You can do that by calling <tt class="docutils literal"><span class="pre">Manager.from_queryset()</span></tt> which
returns a <em>subclass</em> of your base <tt class="docutils literal"><span class="pre">Manager</span></tt> with a copy of the custom
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">BaseManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">manager_only_method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span>

<span class="k">class</span> <span class="nc">CustomQuerySet</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">QuerySet</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">manager_and_queryset_method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span>

<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">BaseManager</span><span class="o">.</span><span class="n">from_queryset</span><span class="p">(</span><span class="n">CustomQueryset</span><span class="p">)()</span>
</pre></div>
</div>
<p>You may also store the generated class into a variable:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">CustomManager</span> <span class="o">=</span> <span class="n">BaseManager</span><span class="o">.</span><span class="n">from_queryset</span><span class="p">(</span><span class="n">CustomQueryset</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">CustomManager</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-custom-managers-and-model-inheritance">
<span id="s-custom-managers-and-inheritance"></span><span id="custom-managers-and-model-inheritance"></span><span id="custom-managers-and-inheritance"></span><h3>Custom managers and model inheritance<a class="headerlink" href="#custom-managers-and-model-inheritance" title="Permalink to this headline">¶</a></h3>
<p>Class inheritance and model managers aren&#8217;t quite a perfect match for each
other. Managers are often specific to the classes they are defined on and
inheriting them in subclasses isn&#8217;t necessarily a good idea. Also, because the
first manager declared is the <em>default manager</em>, it is important to allow that
to be controlled. So here&#8217;s how Django handles custom managers and
<a class="reference internal" href="models.html#model-inheritance"><em>model inheritance</em></a>:</p>
<ol class="arabic simple">
<li>Managers defined on non-abstract base classes are <em>not</em> inherited by
child classes. If you want to reuse a manager from a non-abstract base,
redeclare it explicitly on the child class. These sorts of managers are
likely to be fairly specific to the class they are defined on, so
inheriting them can often lead to unexpected results (particularly as
far as the default manager goes). Therefore, they aren&#8217;t passed onto
child classes.</li>
<li>Managers from abstract base classes are always inherited by the child
class, using Python&#8217;s normal name resolution order (names on the child
class override all others; then come names on the first parent class,
and so on). Abstract base classes are designed to capture information
and behavior that is common to their child classes. Defining common
managers is an appropriate part of this common information.</li>
<li>The default manager on a class is either the first manager declared on
the class, if that exists, or the default manager of the first abstract
base class in the parent hierarchy, if that exists. If no default
manager is explicitly declared, Django&#8217;s normal default manager is
used.</li>
</ol>
<p>These rules provide the necessary flexibility if you want to install a
collection of custom managers on a group of models, via an abstract base
class, but still customize the default manager. For example, suppose you have
this base class:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">AbstractBase</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">CustomManager</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>If you use this directly in a subclass, <tt class="docutils literal"><span class="pre">objects</span></tt> will be the default
manager if you declare no managers in the base class:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">ChildA</span><span class="p">(</span><span class="n">AbstractBase</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="c"># This class has CustomManager as the default manager.</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>If you want to inherit from <tt class="docutils literal"><span class="pre">AbstractBase</span></tt>, but provide a different default
manager, you can provide the default manager on the child class:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">ChildB</span><span class="p">(</span><span class="n">AbstractBase</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="c"># An explicit default manager.</span>
    <span class="n">default_manager</span> <span class="o">=</span> <span class="n">OtherManager</span><span class="p">()</span>
</pre></div>
</div>
<p>Here, <tt class="docutils literal"><span class="pre">default_manager</span></tt> is the default. The <tt class="docutils literal"><span class="pre">objects</span></tt> manager is
still available, since it&#8217;s inherited. It just isn&#8217;t used as the default.</p>
<p>Finally for this example, suppose you want to add extra managers to the child
class, but still use the default from <tt class="docutils literal"><span class="pre">AbstractBase</span></tt>. You can&#8217;t add the new
manager directly in the child class, as that would override the default and you would
have to also explicitly include all the managers from the abstract base class.
The solution is to put the extra managers in another base class and introduce
it into the inheritance hierarchy <em>after</em> the defaults:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">ExtraManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">extra_manager</span> <span class="o">=</span> <span class="n">OtherManager</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>

<span class="k">class</span> <span class="nc">ChildC</span><span class="p">(</span><span class="n">AbstractBase</span><span class="p">,</span> <span class="n">ExtraManager</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="c"># Default manager is CustomManager, but OtherManager is</span>
    <span class="c"># also available via the &quot;extra_manager&quot; attribute.</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>Note that while you can <em>define</em> a custom manager on the abstract model, you
can&#8217;t <em>invoke</em> any methods using the abstract model. That is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">ClassA</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">do_something</span><span class="p">()</span>
</pre></div>
</div>
<p>is legal, but:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">AbstractBase</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">do_something</span><span class="p">()</span>
</pre></div>
</div>
<p>will raise an exception. This is because managers are intended to encapsulate
logic for managing collections of objects. Since you can&#8217;t have a collection of
abstract objects, it doesn&#8217;t make sense to be managing them. If you have
functionality that applies to the abstract model, you should put that functionality
in a <tt class="docutils literal"><span class="pre">staticmethod</span></tt> or <tt class="docutils literal"><span class="pre">classmethod</span></tt> on the abstract model.</p>
</div>
<div class="section" id="s-implementation-concerns">
<span id="implementation-concerns"></span><h3>Implementation concerns<a class="headerlink" href="#implementation-concerns" title="Permalink to this headline">¶</a></h3>
<p>Whatever features you add to your custom <tt class="docutils literal"><span class="pre">Manager</span></tt>, it must be
possible to make a shallow copy of a <tt class="docutils literal"><span class="pre">Manager</span></tt> instance; i.e., the
following code must work:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">copy</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">manager</span> <span class="o">=</span> <span class="n">MyManager</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">my_copy</span> <span class="o">=</span> <span class="n">copy</span><span class="o">.</span><span class="n">copy</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span>
</pre></div>
</div>
<p>Django makes shallow copies of manager objects during certain queries;
if your Manager cannot be copied, those queries will fail.</p>
<p>This won&#8217;t be an issue for most custom managers. If you are just
adding simple methods to your <tt class="docutils literal"><span class="pre">Manager</span></tt>, it is unlikely that you
will inadvertently make instances of your <tt class="docutils literal"><span class="pre">Manager</span></tt> uncopyable.
However, if you&#8217;re overriding <tt class="docutils literal"><span class="pre">__getattr__</span></tt> or some other private
method of your <tt class="docutils literal"><span class="pre">Manager</span></tt> object that controls object state, you
should ensure that you don&#8217;t affect the ability of your <tt class="docutils literal"><span class="pre">Manager</span></tt> to
be copied.</p>
</div>
</div>
<div class="section" id="s-controlling-automatic-manager-types">
<span id="s-manager-types"></span><span id="controlling-automatic-manager-types"></span><span id="manager-types"></span><h2>Controlling automatic Manager types<a class="headerlink" href="#controlling-automatic-manager-types" title="Permalink to this headline">¶</a></h2>
<p>This document has already mentioned a couple of places where Django creates a
manager class for you: <a class="reference internal" href="#manager-names">default managers</a> and the &#8220;plain&#8221; manager used to
<a class="reference internal" href="#managers-for-related-objects">access related objects</a>. There are other places in the implementation of
Django where temporary plain managers are needed. Those automatically created
managers will normally be instances of the <a class="reference internal" href="#django.db.models.Manager" title="django.db.models.Manager"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.Manager</span></tt></a>
class.</p>
<p>Throughout this section, we will use the term &#8220;automatic manager&#8221; to mean a
manager that Django creates for you &#8211; either as a default manager on a model
with no managers, or to use temporarily when accessing related objects.</p>
<p>Sometimes this default class won&#8217;t be the right choice. One example is in the
<a class="reference internal" href="../../ref/contrib/gis/index.html#module-django.contrib.gis" title="django.contrib.gis: Geographic Information System (GIS) extensions for Django"><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.gis</span></tt></a> application that ships with Django itself. All <tt class="docutils literal"><span class="pre">gis</span></tt>
models must use a special manager class (<a class="reference internal" href="../../ref/contrib/gis/model-api.html#django.contrib.gis.db.models.GeoManager" title="django.contrib.gis.db.models.GeoManager"><tt class="xref py py-class docutils literal"><span class="pre">GeoManager</span></tt></a>)
because they need a special queryset (<a class="reference internal" href="../../ref/contrib/gis/geoquerysets.html#django.contrib.gis.db.models.GeoQuerySet" title="django.contrib.gis.db.models.GeoQuerySet"><tt class="xref py py-class docutils literal"><span class="pre">GeoQuerySet</span></tt></a>)
to be used for interacting with the database.  It turns out that models which require
a special manager like this need to use the same manager class wherever an automatic
manager is created.</p>
<p>Django provides a way for custom manager developers to say that their manager
class should be used for automatic managers whenever it is the default manager
on a model. This is done by setting the <tt class="docutils literal"><span class="pre">use_for_related_fields</span></tt> attribute on
the manager class:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="n">use_for_related_fields</span> <span class="o">=</span> <span class="bp">True</span>
    <span class="c"># ...</span>
</pre></div>
</div>
<p>If this attribute is set on the <em>default</em> manager for a model (only the
default manager is considered in these situations), Django will use that class
whenever it needs to automatically create a manager for the class.  Otherwise,
it will use <a class="reference internal" href="#django.db.models.Manager" title="django.db.models.Manager"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.Manager</span></tt></a>.</p>
<div class="admonition-historical-note admonition">
<p class="first admonition-title">Historical Note</p>
<p class="last">Given the purpose for which it&#8217;s used, the name of this attribute
(<tt class="docutils literal"><span class="pre">use_for_related_fields</span></tt>) might seem a little odd. Originally, the
attribute only controlled the type of manager used for related field
access, which is where the name came from. As it became clear the concept
was more broadly useful, the name hasn&#8217;t been changed. This is primarily
so that existing code will <a class="reference internal" href="../../misc/api-stability.html"><em>continue to work</em></a> in
future Django versions.</p>
</div>
<div class="section" id="s-writing-correct-managers-for-use-in-automatic-manager-instances">
<span id="writing-correct-managers-for-use-in-automatic-manager-instances"></span><h3>Writing correct Managers for use in automatic Manager instances<a class="headerlink" href="#writing-correct-managers-for-use-in-automatic-manager-instances" title="Permalink to this headline">¶</a></h3>
<p>As already suggested by the <a class="reference internal" href="../../ref/contrib/gis/index.html#module-django.contrib.gis" title="django.contrib.gis: Geographic Information System (GIS) extensions for Django"><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.gis</span></tt></a> example, above, the
<tt class="docutils literal"><span class="pre">use_for_related_fields</span></tt> feature is primarily for managers that need to
return a custom <tt class="docutils literal"><span class="pre">QuerySet</span></tt> subclass. In providing this functionality in your
manager, there are a couple of things to remember.</p>
<div class="section" id="s-do-not-filter-away-any-results-in-this-type-of-manager-subclass">
<span id="do-not-filter-away-any-results-in-this-type-of-manager-subclass"></span><h4>Do not filter away any results in this type of manager subclass<a class="headerlink" href="#do-not-filter-away-any-results-in-this-type-of-manager-subclass" title="Permalink to this headline">¶</a></h4>
<p>One reason an automatic manager is used is to access objects that are related
to from some other model. In those situations, Django has to be able to see
all the objects for the model it is fetching, so that <em>anything</em> which is
referred to can be retrieved.</p>
<p>If you override the <tt class="docutils literal"><span class="pre">get_queryset()</span></tt> method and filter out any rows, Django
will return incorrect results. Don&#8217;t do that. A manager that filters results
in <tt class="docutils literal"><span class="pre">get_queryset()</span></tt> is not appropriate for use as an automatic manager.</p>
</div>
<div class="section" id="s-set-use-for-related-fields-when-you-define-the-class">
<span id="set-use-for-related-fields-when-you-define-the-class"></span><h4>Set <tt class="docutils literal"><span class="pre">use_for_related_fields</span></tt> when you define the class<a class="headerlink" href="#set-use-for-related-fields-when-you-define-the-class" title="Permalink to this headline">¶</a></h4>
<p>The <tt class="docutils literal"><span class="pre">use_for_related_fields</span></tt> attribute must be set on the manager <em>class</em>, not
on an <em>instance</em> of the class. The earlier example shows the correct way to set
it, whereas the following will not work:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># BAD: Incorrect code</span>
<span class="k">class</span> <span class="nc">MyManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">pass</span>

<span class="c"># Sets the attribute on an instance of MyManager. Django will</span>
<span class="c"># ignore this setting.</span>
<span class="n">mgr</span> <span class="o">=</span> <span class="n">MyManager</span><span class="p">()</span>
<span class="n">mgr</span><span class="o">.</span><span class="n">use_for_related_fields</span> <span class="o">=</span> <span class="bp">True</span>

<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">mgr</span>

<span class="c"># End of incorrect code.</span>
</pre></div>
</div>
<p>You also shouldn&#8217;t change the attribute on the class object after it has been
used in a model, since the attribute&#8217;s value is processed when the model class
is created and not subsequently reread. Set the attribute on the manager class
when it is first defined, as in the initial example of this section and
everything will work smoothly.</p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Managers</a><ul>
<li><a class="reference internal" href="#manager-names">Manager names</a></li>
<li><a class="reference internal" href="#custom-managers">Custom Managers</a><ul>
<li><a class="reference internal" href="#adding-extra-manager-methods">Adding extra Manager methods</a></li>
<li><a class="reference internal" href="#modifying-initial-manager-querysets">Modifying initial Manager QuerySets</a><ul>
<li><a class="reference internal" href="#default-managers">Default managers</a></li>
<li><a class="reference internal" href="#using-managers-for-related-object-access">Using managers for related object access</a></li>
</ul>
</li>
<li><a class="reference internal" href="#calling-custom-queryset-methods-from-the-manager">Calling custom <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods from the <tt class="docutils literal"><span class="pre">Manager</span></tt></a></li>
<li><a class="reference internal" href="#creating-manager-with-queryset-methods">Creating <tt class="docutils literal"><span class="pre">Manager</span></tt> with <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods</a><ul>
<li><a class="reference internal" href="#from-queryset">from_queryset</a></li>
</ul>
</li>
<li><a class="reference internal" href="#custom-managers-and-model-inheritance">Custom managers and model inheritance</a></li>
<li><a class="reference internal" href="#implementation-concerns">Implementation concerns</a></li>
</ul>
</li>
<li><a class="reference internal" href="#controlling-automatic-manager-types">Controlling automatic Manager types</a><ul>
<li><a class="reference internal" href="#writing-correct-managers-for-use-in-automatic-manager-instances">Writing correct Managers for use in automatic Manager instances</a><ul>
<li><a class="reference internal" href="#do-not-filter-away-any-results-in-this-type-of-manager-subclass">Do not filter away any results in this type of manager subclass</a></li>
<li><a class="reference internal" href="#set-use-for-related-fields-when-you-define-the-class">Set <tt class="docutils literal"><span class="pre">use_for_related_fields</span></tt> when you define the class</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="aggregation.html">Aggregation</a></li>
    
    
      <li>Next: <a href="sql.html">Performing raw SQL queries</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../index.html">Using Django</a>
        
          <ul><li><a href="index.html">Models and databases</a>
        
        <ul><li>Managers</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/topics/db/managers.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="aggregation.html" title="Aggregation">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="sql.html" title="Performing raw SQL queries">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>